import { watchEffect, computed, onUnmounted } from 'vue'
import { refToRaw, limitTrigger } from '../../utils'
import { subscribe } from '../../utils/listener'

import type { FP } from '../../types'

const useRefreshOnWindowFocus: FP = (fetchInstance, { refreshOnWindowFocus = false, refocusInterval = 5000 }) => {
  const refreshOnWindowFocusRef = computed(() => refToRaw(refreshOnWindowFocus))
  const refocusIntervalRef = computed(() => refToRaw(refocusInterval))

  const unsubscribeList: (() => void)[] = []
  const addUnsubscribeList = (event?: () => void) => {
    event && unsubscribeList.push(event)
  }
  const unsubscribe = () => {
    unsubscribeList.forEach(fn => fn())
    unsubscribeList.length = 0
  }

  watchEffect(() => {
    unsubscribe()

    if (refreshOnWindowFocusRef.value) {
      const limitRefresh = limitTrigger(fetchInstance.context.refresh, refocusIntervalRef.value)
      addUnsubscribeList(subscribe('FOCUS_LISTENER', limitRefresh))
      addUnsubscribeList(subscribe('VISIBLE_LISTENER', limitRefresh))
    }
  })

  onUnmounted(() => {
    unsubscribe()
  })

  return {}
}

export default useRefreshOnWindowFocus
